﻿using System;
using System.Web.Security;
using SBACN.WebSite.Cache;
using SBACN.WebSite.Code;
using SBACN.WebSite.Models;
using SBACN.WebSite.UC;

namespace SBACN.WebSite
{
	public partial class Login : BasePage
	{
		public string ReturnURL
		{
			get
			{
				if(ViewState["ReturnURL"] == null)//string.IsNullOrWhiteSpace(ViewState["ReturnURL"]))
				{
					return string.Empty;
				}
				return ViewState["ReturnURL"].ToString();
			}
			private set
			{
				ViewState["ReturnURL"] = value;
			}
		}
		protected void Page_Load(object sender, EventArgs e)
		{
			if(!Page.IsPostBack)
			{
				if(Request.UrlReferrer != null && !string.IsNullOrWhiteSpace(Request.UrlReferrer.OriginalString) && Request.Url.Host.ToLower() == Request.UrlReferrer.Host.ToLower())
				{
					ReturnURL = Request.UrlReferrer.OriginalString;
				}
				else if (!string.IsNullOrWhiteSpace(Request["returl"]))
				{
					string returl = Server.UrlDecode(Request["returl"].Trim());
					Uri u = null;
					if (Uri.TryCreate(returl, UriKind.Relative, out u))
					{
						ReturnURL = returl;
					}
					else if (Uri.TryCreate(returl, UriKind.Absolute, out u))
					{
						if(u.Host.ToLower() == Request.Url.Host.ToLower())
						{
							ReturnURL = returl;
						}
					}
				}
			}
		}
		
		protected void btn_Login_Click(object sender, EventArgs e)
		{
			string name = txt_UserName.Text.Trim();
			string password = hid_Password.Value.Trim().ToLower();
			if (string.IsNullOrEmpty(name))
			{
				this.lbl_Msg.Text = "用户名不能为空!";
				return;
			}
			string emptyMD5 = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Empty, "MD5").ToLower();
			if (string.IsNullOrWhiteSpace(password) || password == emptyMD5)
			{
				this.lbl_Msg.Text = "密码不能为空!";
				return;
			}

			password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5").ToLower();
			TB_User user = DAL.DALHelper.Instance.GetObject<TB_User>("UserName", name);
			if (user != null && user.Password == password)
			{
				if (user.Status && UserRightCache.Instance[user.UserName].Count > 0)
				{
					user.LastLoginIP = user.LoginIP;
					user.LastLoginTime = user.LoginTime;
					user.LoginIP = BasePage.GetRequestIP(Request);
					user.LoginTime = DateTime.Now;
					user.LoginCount++;
					DAL.DALHelper.Instance.Update(user);
					DAL.DALHelper.Instance.SaveChanges();
					Session["UserInfo"] = user;
					this.lbl_Msg.Text = string.Empty;

					var header = this.Master.FindControl("Header1") as Header;

					if (header != null)
					{
						header.InitCtrl();
					}
					if(!string.IsNullOrWhiteSpace(ReturnURL))
					{
						Response.Redirect(ReturnURL);
					}
					else
					{
						Response.Redirect(BasePage.MemberDefaultPage);
					}
				}
				else
				{
					this.lbl_Msg.Text = "禁止登录!";
				}
			}
			else
			{
				this.lbl_Msg.Text = "用户名、密码不匹配!";
			}
		}
	}
}